/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.phoenix.repository.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import javax.jcr.AccessDeniedException;
import javax.jcr.InvalidItemStateException;
import javax.jcr.ItemExistsException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.PropertyType;
import javax.jcr.ReferentialIntegrityException;
import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.ValueFormatException;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.nodetype.PropertyDefinition;
import javax.jcr.version.VersionException;

import net.phoenix.repository.JCRUtils;

import org.xml.sax.SAXException;

/**
 * Jigsaw server
 * 
 * @author <a href="shamphone@gmail.com">Li XiongFeng</a>
 * @date 2012-5-5
 * @version 1.0.0
 */
public class CreateContentHandler extends GeneralContentHandler {
	protected Stack<Node> nodes;
	protected int propertyType;
	protected String propertyName;
	protected List<Value> values;
	protected ValueFactory factory;
	protected StringBuffer value;
	protected String nodeType;

	private static String NAME_PRIMARY_TYPE = "jcr:primaryType";
	private static String NAME_MIXIN_TYPES = "jcr:mixinTypes";
	private static String NAME_UUID = "UUID";
	private static String[] ReservedPropertyName = { NAME_PRIMARY_TYPE, NAME_MIXIN_TYPES, NAME_UUID };

	public CreateContentHandler(Node parent) {
		if(parent==null)
			throw new NullPointerException("parent node should not be null.");
		this.nodes = new Stack<Node>();
		this.nodes.push(parent);
		this.values = new ArrayList<Value>();
		this.value = new StringBuffer();
		try {
			this.factory = parent.getSession().getValueFactory();
		} catch (UnsupportedRepositoryOperationException e) {
			throw new UnsupportedOperationException(e);
		} catch (RepositoryException e) {
			throw new UnsupportedOperationException(e);
		}
	}

	/**
	 * 
	 * @param name
	 * @throws RepositoryException
	 * @throws LockException
	 * @throws ConstraintViolationException
	 * @throws VersionException
	 * @throws PathNotFoundException
	 * @throws ItemExistsException
	 */
	protected void startNode(String name) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException {
		Node parent = (Node) this.nodes.peek();
		Node node = parent.addNode(name);
		this.nodes.push(node);
	}

	/**
	 * 
	 * @param name
	 * @throws RepositoryException
	 */
	protected void startProperty(String name) throws RepositoryException {
		Node parent = (Node) this.nodes.peek();
		if(parent==null)
			throw new NullPointerException("parent node should not be null.");
		if (!this.isReservedPropertyName(name)) {
			PropertyDefinition definition = JCRUtils.getPropertyDefinition(parent, name);
			if(definition == null)
				throw new IllegalArgumentException("No property definition with '"+name+"' in node "+parent.getIdentifier());
		} else
			this.propertyType = PropertyType.STRING;
		this.propertyName = name;
		this.values.clear();
	}

	private boolean isReservedPropertyName(String property) {
		for (String name : ReservedPropertyName) {
			if (name.equalsIgnoreCase(property))
				return true;
		}
		return false;
	}

	/**
	 * 
	 */
	protected void startValue() {
		this.value = new StringBuffer();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.xml.sax.ContentHandler#characters(char[], int, int)
	 */
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		this.value.append(new String(ch, start, length));
	}

	/**
	 * @throws ValueFormatException
	 * 
	 */
	protected void endValue() throws ValueFormatException {
		this.values.add(this.factory.createValue(value.toString(), this.propertyType));
	}

	/**
	 * 
	 * @param name
	 * @throws RepositoryException
	 * @throws ConstraintViolationException
	 * @throws LockException
	 * @throws VersionException
	 * @throws ValueFormatException
	 */
	protected void endProperty() throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
		Node node = this.nodes.peek();
		if (propertyName.equalsIgnoreCase(NAME_PRIMARY_TYPE)) {
			node.setPrimaryType(this.values.get(0).getString());
		} else if (propertyName.equalsIgnoreCase(NAME_MIXIN_TYPES)) {
			for (Value mixin : this.values)
				node.addMixin(mixin.getString());
		} else
			node.setProperty(this.propertyName, this.values.toArray(new Value[this.values.size()]));
	}

	/**
	 * 
	 * @param name
	 * @throws RepositoryException
	 * @throws NoSuchNodeTypeException
	 * @throws LockException
	 * @throws VersionException
	 * @throws ReferentialIntegrityException
	 * @throws InvalidItemStateException
	 * @throws ConstraintViolationException
	 * @throws ItemExistsException
	 * @throws AccessDeniedException
	 */
	protected void endNode() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException,
			LockException, NoSuchNodeTypeException, RepositoryException {
		this.nodes.pop();
	}

}
